package com.fxd.serviceorder.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fxd.model.order.bean.Order;
import com.fxd.model.product.bean.Product;
import com.fxd.serviceorder.feign.ProductFeignClient;
import com.fxd.serviceorder.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.math.BigDecimal;
import java.util.Arrays;

/**
 * @author xudongfu
 * @date 2025/06/08
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Autowired
    private ProductFeignClient productFeignClient;

    @SentinelResource(value = "createOrder", blockHandler = "createOrderFallBack")
    @Override
    public Order createOrder(Long productId, Long userId) {

        Product product = productFeignClient.getProductById(productId);

        Order order = new Order();
        order.setId(1L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(userId);
        order.setNickName("lisi");
        order.setAddress("长沙");
        order.setProductList(Arrays.asList(product));

        return order;
    }

    public Order createOrderFallBack(Long productId, Long userId, BlockException e) {

        Order order = new Order();
        order.setId(0L);
        order.setTotalAmount(new BigDecimal("0"));
        order.setUserId(0L);
        order.setNickName("createOrderFallBack");
        order.setAddress(e.getClass().toString());
        order.setProductList(null);

        return order;
    }

    /**
     * API负载均衡调用
     */
    private Product getProductByLoadBalancerClient(Long productId) {

        ServiceInstance instance = loadBalancerClient.choose("service-product");

        String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/product/" + productId;

        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }

    /**
     * 注解负载均衡调用
     */
    private Product getProductByLoadBalancerAnnotation(Long productId) {


        String url = "http://service-product/product/" + productId;

        Product product = restTemplate.getForObject(url, Product.class);
        return product;
    }
}
